﻿using System;
using System.Collections.ObjectModel;
using System.Threading;
using PoolKit.Commands;

namespace PoolKit
{
    /// <summary>
    /// </summary>
    /// <typeparam name="TResource"></typeparam>
    internal class ResourceEvictionManager<TResource> : IDisposable
        where TResource : class
    {
        private readonly IResourceCollectionUsageTracking<TResource> _resourceCollection;
        private readonly ICommandProcessor _commandProcessor;
        private bool _monitoring;
        private readonly DisposableCookie _disposableCookie = new DisposableCookie(Resources.MonitorAlreadyDisposed);
        private readonly object _stateChangeCriticalSection = new object();
        private bool _scheduledEviction;
        private readonly TimeSpan _minimumResourceIdleTime;
        private readonly int _minimumCountOfResourcesForEvictionToKickIn;
        private CancellationTokenSource _cancellationToken;

        public ResourceEvictionManager(
            ICommandProcessor commandProcessor,
            IResourceCollectionUsageTracking<TResource> resourceCollection,
            TimeSpan minimumResourceIdleTime,
            int minimumCountOfResourcesForEvictionToKickIn)
        {
            if (commandProcessor == null) throw new ArgumentNullException("commandProcessor");

            if (resourceCollection == null)
                throw new ArgumentNullException("resourceCollection");

            if (minimumCountOfResourcesForEvictionToKickIn < 0)
            {
                throw new ArgumentOutOfRangeException("minimumCountOfResourcesForEvictionToKickIn", Resources.ExpectingNonNegativeNumber);
            }

            if (minimumResourceIdleTime < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("minimumResourceIdleTime", Resources.NegativeTimeSpansNotAllowed);
            }

            _resourceCollection = resourceCollection;
            _minimumCountOfResourcesForEvictionToKickIn = minimumCountOfResourcesForEvictionToKickIn;
            _minimumResourceIdleTime = minimumResourceIdleTime;
            _commandProcessor = commandProcessor;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        public void Start()
        {
            _disposableCookie.ThrowIfDisposed();

            if (_monitoring)
            {
                throw new InvalidOperationException(Resources.CannotStartMonitorThatIsRunning);
            }

            _cancellationToken = new CancellationTokenSource();

            _monitoring = true;

            _resourceCollection.ItemCountUp += ResourceCollectionItemCountUp;

            ScheduleEviction();
        }

        public void Stop()
        {
            _disposableCookie.ThrowIfDisposed();

            if (!_monitoring)
            {
                throw new InvalidOperationException(Resources.CannotStopMonitorThatIsStopped);
            }

            _monitoring = false;

            _resourceCollection.ItemCountUp -= ResourceCollectionItemCountUp;

            _cancellationToken.Cancel();
        }

        private bool IsCancelled()
        {
            return _cancellationToken.IsCancellationRequested;
        }

        private bool IsResourceCountSufficientToEvictAnything()
        {
            return (_resourceCollection.Count > _minimumCountOfResourcesForEvictionToKickIn);
        }

        private void ResourceCollectionItemCountUp(object sender, EventArgs e)
        {
            ScheduleEviction();
        }

        /// <summary>
        ///
        /// </summary>
        private void ScheduleEviction()
        {
            // TODO: this hurts scalability, but will do for an early release
            lock (_stateChangeCriticalSection)
            {
                if (_scheduledEviction || !IsResourceCountSufficientToEvictAnything() || IsCancelled())
                {
                    return;
                }

                try
                {
                    TimeSpan maxResourceIdleTime = _resourceCollection.GetMaxResourceIdleTime();

                    TimeSpan amountOfTimeToWaitBeforeRunningCommand = (_minimumResourceIdleTime - maxResourceIdleTime);

                    if (amountOfTimeToWaitBeforeRunningCommand < TimeSpan.Zero)
                    {
                        amountOfTimeToWaitBeforeRunningCommand = TimeSpan.Zero;
                    }

                    _commandProcessor.RegisterDelayedCommand(
                        new ActionCommand(EvictAndReschedule),
                        amountOfTimeToWaitBeforeRunningCommand);

                    _scheduledEviction = true;
                }
                catch (ResourceCollectionEmptyException)
                {
                    // no work to do, then. Nothing gets scheduled.
                }
            }
        }

        private void EvictAndReschedule()
        {
            lock (_stateChangeCriticalSection)
            {
                // first thing to do: resetting the flag inside the scheduled routine
                _scheduledEviction = false;

                EvictIdleResources();
                ScheduleEviction();
            }
        }

        private void EvictIdleResources()
        {
            ReadOnlyCollection<TResource> resourcesToEvict =
                _resourceCollection.GetResourcesSittingIdle(_minimumResourceIdleTime);

            for (int i = 0; i < resourcesToEvict.Count && IsResourceCountSufficientToEvictAnything() && !IsCancelled(); i++)
            {
                _resourceCollection.TryEvict(resourcesToEvict[i]);
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(false);
        }

        private void Dispose(bool calledFromFinalizer)
        {
            if (_disposableCookie.IsDisposed)
            {
                return;
            }

            if (_monitoring)
            {
                Stop();
            }

            _disposableCookie.MarkAsDisposed();
        }
    }
}